//
//  main.cpp
//  opencv_project
//
//  Created by 黄琛 on 2018/12/25.
//  Copyright © 2018 黄琛. All rights reserved.
//

#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include <iostream>
using namespace cv;
using namespace std;

Mat hist(Mat img)
{
    MatND dstHist;//得到的直方图
    int dims = 1;//得到的直方图的维数 灰度图的维数为1
    float hranges[2] = { 0, 255 };
    const float *ranges[1] = { hranges };   // 这里需要为const类型，二维数组用来指出每个区间的范围
    int size = 256;//直方图横坐标的区间数 即横坐标被分成256份
    int channels = 0;//图像的通道 灰度图的通道数为0
    //计算图像的直方图
    calcHist(&img, 1, &channels, Mat(), dstHist, dims, &size, ranges);
    int scale = 1;
    Mat dstImage(size * scale, size, CV_8U, Scalar(0));
    //获取最大值和最小值
    double minValue = 0;
    double maxValue = 0;
    minMaxLoc(dstHist, &minValue, &maxValue, 0, 0); //找到直方图中的最大值和最小值
    //绘制出直方图
    int hpt = saturate_cast<int>(0.9 * size);//防止溢出
    for (int i = 0; i < 256; i++)
    {
        float binValue = dstHist.at<float>(i);
        int realValue = saturate_cast<int>(binValue * hpt / maxValue);
        line(dstImage, Point(i*scale, size - 1), Point((i + 1)*scale - 1, size - realValue), Scalar(255));
    }
    return dstImage;
}

int main()
{
    //load the images
//    Mat srcImage1 = imread("pollen1.png");
//    Mat srcImage2 = imread("pollen2.png");
    Mat srcImage = imread("rice2.png");
    
    //resize two images
//    Mat rs_img1, rs_img2;
//    pyrDown(srcImage1, rs_img1);
//    pyrDown(srcImage2, rs_img2);
    
    //计算灰度直方图
//    Mat h1, h2;
//    h1 = hist(rs_img1);
//    h2 = hist(rs_img2);
    Mat h = hist(srcImage);
    
    //show the results
//    imshow("pollen1", rs_img1);
//    imshow("pollen2", rs_img2);
//    imshow("hist of pollen1", h1);
//    imshow("hist of pollen2", h2);
    imshow("Source", srcImage);
    imshow("hist of rice", h);
    
    waitKey(0);
    
    return 0;
}
